package com.wjv.example.springboot.base.service;

import com.wjv.example.common.ResultInfo;
import com.wjv.example.springboot.base.dao.UserInfoRepository;
import com.wjv.example.springboot.base.entity.UserInfoEntity;
import com.wjv.example.springboot.base.event.SentMqEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

/**
 * <p>Title: MySaveService</p>
 *
 * @author wjv
 * @date 2021/6/16 11:10
 */
@Service
public class MySaveService {
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private ApplicationEventPublisher publisher;


    @Transactional
    public ResultInfo saveUser() {
        UserInfoEntity entity = new UserInfoEntity();
        entity.setUserName(String.valueOf(System.currentTimeMillis() / 100));
        entity.setPhoneNum(String.valueOf(System.currentTimeMillis() / 100));
        userInfoRepository.save(entity);

        // 事件发布
        publisher.publishEvent(new SentMqEvent(this, entity));

        Random random = new Random();
        int r = random.nextInt();
        System.out.println(r);
        if ((r % 2) == 0) {
            throw new RuntimeException("主动抛出异常");
        }

        return ResultInfo.success(entity);
    }
}
